package com.ccx.demo.Handler;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyError {

    @Component
    public static class MyAuthenticationEntry implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request,
                             HttpServletResponse response,
                             AuthenticationException authException) throws IOException {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            // 直接提示前端认证错误信息
            out.write(authException.getLocalizedMessage());
            out.flush();
            out.close();
        }
    }

    @Component
    public static class MyAccessDenied implements AccessDeniedHandler {
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
            //角色权限认证失败
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("没有权限进行该操作");
            out.flush();
            out.close();
        }
    }

}
